﻿
#region 作者和版权
/*************************************************************************************
* CLR 版本: 4.0.30319.42000
* 类 名 称: HttpUtility
* 机器名称: SUNTIA-QL
* 命名空间: ServerFramework.Net.Http
* 文 件 名: HttpUtility
* 创建时间: 2015/9/21 18:13:49
* 作 者: 乔龙 Qiaolong
* 版 权: HttpUtility说明：本代码版权归乔龙所有，使用时必须带上乔龙网站地址 All Rights Reserved (C) 2015 - 2013
* 签 名: To be or not, it is not a problem !
* 网 站: http://www.suntia.net
* 邮 箱: qiaolong306@qq.com 
* 唯一标识： b7934160-218d-46c3-96e9-2078559e24d5 
*
* 登录用户: simida
* 所 属 域: SUNTIA-QL

* 创建年份: 2015
* 修改时间:
* 修 改 人:
* 
************************************************************************************/
#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ServerFramework.Net.Msg;
using ServerFramework.Tools;
using System.IO;

namespace ServerFramework.Net.Http
{
    /// <summary>
    /// http 工具类
    /// </summary>
    public static class HttpUtility
    {
        /// <summary>
        /// 异步http请求
        /// </summary>
        /// <param name="data">请求的数据</param>
        /// <param name="url">请求的url</param>
        /// <param name="callback">返回结果回调</param>
        public static void HttpReqAsync(byte[] data, string url, Action<byte[]> callback)
        { 
            Task.Factory.StartNew(()=>
            {
                try
                {
                    WebClient m_web = new WebClient();
                    byte[] recvData = m_web.UploadData(url, data);
                    if (callback != null)
                    {
                        callback(recvData);
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLog(ELogLevel.LOG_ERROR, e.Message);
                }
            });
        }
        /// <summary>
        /// http请求
        /// </summary>
        /// <param name="data">要请求的数据</param>
        /// <param name="url">请求的url</param>
        /// <returns>返回结果</returns>
        public static byte[] HttpReq(byte[] data, string url)
        {
            WebClient web = new WebClient();
            try
            {
                byte[] recvData = web.UploadData(url, data);
                return recvData;
            }
            catch (Exception e)
            {
                Log.WriteLog(ELogLevel.LOG_ERROR, e.Message);
            }
            return null;
        }

        /// <summary>
        /// 获取http键值对
        /// </summary>
        /// <param name="requst">http 请求</param>
        /// <returns></returns>
        public static NameValueCollection GetNameValues(System.Net.HttpListenerRequest request)
        {
            string querystring = "";
            if (request.HttpMethod == "POST")
            {
                byte[] buffer = new byte[request.ContentLength64];
                request.InputStream.Read(buffer, 0, (int)request.ContentLength64);
                querystring = Encoding.UTF8.GetString(buffer);
            }
            else if (request.HttpMethod == "GET")
            {
                int index = request.RawUrl.IndexOf('?');
                if (index != -1)
                {
                    querystring = request.RawUrl.Remove(0, index + 1);
                }
            }
            NameValueCollection nameValues = System.Web.HttpUtility.ParseQueryString(querystring);
            return nameValues;
        }

        /// <summary>
        /// 获取http键值对
        /// </summary>
        /// <param name="requst">http 请求</param>
        /// <returns></returns>
        public static NameValueCollection GetNameValues(HttpWebResponse response)
        {
            string querystring = "";
            if (response.Method == "POST")
            {
                byte[] buffer = new byte[response.ContentLength];
                using (Stream stream = response.GetResponseStream())
                {
                    stream.Read(buffer, 0, (int)response.ContentLength);
                }
                querystring = Encoding.UTF8.GetString(buffer);
            }
            else if (response.Method == "GET")
            {
                int index = response.ResponseUri.ToString().IndexOf('?');
                if (index != -1)
                {
                    querystring = response.ResponseUri.ToString().Remove(0, index + 1);
                }
            }
            NameValueCollection nameValues = System.Web.HttpUtility.ParseQueryString(querystring);
            return nameValues;
        }

        public static string UrlDecode(string s)
        {
            return System.Web.HttpUtility.UrlDecode(s);
        }

        /// <summary>
        /// 获取http请求的数据包
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static MsgPacket GetMsgPacket(System.Net.HttpListenerRequest request)
        {
            if (request.HttpMethod != "POST")
            {
                return null;
            }
            byte[] buffer = new byte[request.ContentLength64];
            request.InputStream.Read(buffer, 0, (int)request.ContentLength64);
            MsgPacket packet = MsgPacket.SplitPacket(request, buffer, 0, buffer.Length);
            return packet;
        }

        public static string GetRequestIp(System.Net.HttpListenerRequest request)
        {
            return request.RemoteEndPoint.Address.ToString();
        }


        /// <summary>
        /// 获取http键值对
        /// </summary>
        /// <param name="requst">http 请求</param>
        /// <returns></returns>
        public static NameValueCollection GetNameValues(string response)
        {
            NameValueCollection nameValues = System.Web.HttpUtility.ParseQueryString(response);
            return nameValues;
        }



        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            byte [] buffer = null;
            using (Stream myRequestStream = request.GetRequestStream())
            {
                buffer = (Encoding.UTF8.GetBytes(postDataStr));
                myRequestStream.Write(buffer,0,buffer.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public static string HttpPost(string Url, Dictionary<string,string> postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string postDataStr = NameValuesToString(postData);
            byte[] buffer = Encoding.UTF8.GetBytes(postDataStr);
            request.ContentLength = buffer.Length;
            using (Stream myRequestStream = request.GetRequestStream())
            {
                myRequestStream.Write(buffer, 0, buffer.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(myResponseStream,Encoding.UTF8))
                {
                   return reader.ReadToEnd();
                }
            }
        }

        public static string HttpGet(string Url, Dictionary<string,string> getData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + "?" + NameValuesToString(getData));
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }


        public static string NameValuesToString(Dictionary<string,string> nvs)
        {
            string result = "";
            List<string> keys = new List<string>(nvs.Keys);
            List<string> vals = new List<string>(nvs.Values);
            for (int i = 0; i < keys.Count; ++i)
            {
                if (i != keys.Count - 1)
                {
                    result += keys[i] + "=" + vals[i] + "&";
                }
                else
                {
                    result += keys[i] + "=" + vals[i];
                }
            }
            return result;

        }

        public async static Task<string> HttpPostAsync(string Url, Dictionary<string, string> postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string postDataStr = NameValuesToString(postData);
            byte[] buffer = Encoding.UTF8.GetBytes(postDataStr);
            request.ContentLength = buffer.Length;
            using (Stream myRequestStream = request.GetRequestStream())
            {
                myRequestStream.Write(buffer, 0, buffer.Length);
            }
            return await Task.Run<string>(() =>
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream myResponseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                });
        }

        public async static Task<string> HttpGetAsync(string Url, Dictionary<string, string> getData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + "?" + NameValuesToString(getData));
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            return await Task.Run<string>(() =>
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream myResponseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                    {
                        return reader.ReadToEnd();
                    }
                }
            });
        }


    }
}


